<template>
  <div class="category-manager">
    <div class="category-header">
      <h3>文件分类</h3>
      <a-button type="primary" @click="openAddCategoryModal" v-if="isAdmin">
        <template #icon><plus-outlined /></template>
        添加分类
      </a-button>
    </div>

    <div class="category-list">
      <div v-for="category in categories" :key="category.id" class="category-item" :class="{ active: selectedCategory[0] === category.id }" @click="selectCategory(category.id)">
        <div class="category-info">
          <folder-outlined class="category-icon" />
          <span class="category-name">{{ category.name }}</span>
          <span class="file-count">({{ getFileCount(category.id) }})</span>
        </div>
        <div class="category-actions" v-if="category.id !== 'all' && isAdmin">
          <a-button type="text" size="small" @click.stop="openEditCategoryModal(category)">
            <template #icon><edit-outlined /></template>
          </a-button>
          <a-button type="text" size="small" danger @click.stop="deleteCategory(category)">
            <template #icon><delete-outlined /></template>
          </a-button>
        </div>
      </div>
    </div>

    <!-- 添加分类模态框 -->
    <a-modal v-model:open="addCategoryModalVisible" title="添加分类" @ok="handleAddCategory" @cancel="resetAddCategoryForm">
      <a-form :model="addCategoryForm" :rules="addCategoryRules" ref="addCategoryFormRef">
        <a-form-item label="分类名称" name="name">
          <a-input v-model:value="addCategoryForm.name" placeholder="请输入分类名称" @pressEnter="handleAddCategory" />
        </a-form-item>
        <a-form-item label="分类描述" name="description">
          <a-textarea v-model:value="addCategoryForm.description" placeholder="请输入分类描述（可选）" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑分类模态框 -->
    <a-modal v-model:open="editCategoryModalVisible" title="编辑分类" @ok="handleEditCategory" @cancel="resetEditCategoryForm">
      <a-form :model="editCategoryForm" :rules="editCategoryRules" ref="editCategoryFormRef">
        <a-form-item label="分类名称" name="name">
          <a-input v-model:value="editCategoryForm.name" placeholder="请输入分类名称" @pressEnter="handleEditCategory" />
        </a-form-item>
        <a-form-item label="分类描述" name="description">
          <a-textarea v-model:value="editCategoryForm.description" placeholder="请输入分类描述（可选）" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { PlusOutlined, FolderOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { useFileStorageStore } from '@/stores/fileStorage'
import { useUserStore } from '@/stores/user'

// 使用store
const fileStorageStore = useFileStorageStore()
const userStore = useUserStore()

// 响应式数据
const addCategoryModalVisible = ref(false)
const editCategoryModalVisible = ref(false)
const addCategoryFormRef = ref()
const editCategoryFormRef = ref()

// 表单数据
const addCategoryForm = ref({
  name: '',
  description: ''
})

const editCategoryForm = ref({
  id: '',
  name: '',
  description: ''
})

// 表单验证规则
const addCategoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 20, message: '分类名称长度在1到20个字符', trigger: 'blur' }
  ]
}

const editCategoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 20, message: '分类名称长度在1到20个字符', trigger: 'blur' }
  ]
}

// 计算属性
const categories = computed(() => fileStorageStore.categories)
const selectedCategory = computed(() => fileStorageStore.selectedCategory)
const isAdmin = computed(() => {
  return userStore.isAuthenticated && (userStore.user?.username === 'woaichitudouo' || userStore.user?.username === 'woaichitudou')
})

// 方法
const selectCategory = async (categoryId) => {
  await fileStorageStore.selectCategory(categoryId)
}

const getFileCount = (categoryId) => {
  if (categoryId === 'all') {
    return fileStorageStore.totalFilesCount
  }
  // 从categories数据中获取file_count
  const category = fileStorageStore.categories.find((cat) => cat.id === categoryId)
  return category?.file_count || 0
}

const openAddCategoryModal = () => {
  addCategoryModalVisible.value = true
}

const openEditCategoryModal = (category) => {
  editCategoryForm.value = {
    id: category.id,
    name: category.name,
    description: category.description || ''
  }
  editCategoryModalVisible.value = true
}

const handleAddCategory = async () => {
  try {
    await addCategoryFormRef.value.validate()

    await fileStorageStore.addCategory(addCategoryForm.value)
    message.success('分类添加成功')
    addCategoryModalVisible.value = false
    resetAddCategoryForm()
  } catch (error) {
    if (error.errorFields) {
      // 表单验证错误
      return
    }
    message.error(error.message || '添加分类失败')
  }
}

const handleEditCategory = async () => {
  try {
    await editCategoryFormRef.value.validate()

    await fileStorageStore.updateCategory(editCategoryForm.value.id, {
      name: editCategoryForm.value.name,
      description: editCategoryForm.value.description
    })
    message.success('分类更新成功')
    editCategoryModalVisible.value = false
    resetEditCategoryForm()
  } catch (error) {
    if (error.errorFields) {
      // 表单验证错误
      return
    }
    message.error(error.message || '更新分类失败')
  }
}

const deleteCategory = (category) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除分类"${category.name}"吗？该分类下的文件将被移动到其他分类。`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await fileStorageStore.deleteCategory(category.id)
        message.success('分类删除成功')
      } catch (error) {
        message.error(error.message || '删除分类失败')
      }
    }
  })
}

const resetAddCategoryForm = () => {
  addCategoryForm.value = {
    name: '',
    description: ''
  }
  addCategoryFormRef.value?.resetFields()
}

const resetEditCategoryForm = () => {
  editCategoryForm.value = {
    id: '',
    name: '',
    description: ''
  }
  editCategoryFormRef.value?.resetFields()
}
</script>

<style scoped>
.category-manager {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 240px);
  max-height: calc(100vh - 240px);
  display: flex;
  flex-direction: column;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.category-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.category-list {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 4px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.category-item:hover {
  background: #f5f5f5;
  border-color: #d9d9d9;
}

.category-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.category-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.category-icon {
  margin-right: 8px;
  color: #1890ff;
  font-size: 16px;
}

.category-name {
  font-size: 14px;
  color: #262626;
  margin-right: 8px;
}

.file-count {
  font-size: 12px;
  color: #8c8c8c;
}

.category-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.category-item:hover .category-actions {
  opacity: 1;
}

.category-actions .ant-btn {
  padding: 4px 8px;
  height: auto;
  border: none;
  box-shadow: none;
}

.category-actions .ant-btn:hover {
  background: rgba(0, 0, 0, 0.06);
}

/* 滚动条样式 */
.category-list::-webkit-scrollbar {
  width: 6px;
}

.category-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.category-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.category-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .category-manager {
    height: auto;
    max-height: 500px;
  }
}

@media (max-width: 768px) {
  .category-manager {
    height: auto;
    max-height: 400px;
  }
}
</style>
